/*
 * Created on Aug 8, 2008
 * 
 */
package com.scalar.chiptrack.adaptor.ikanos.ams;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import com.scalar.ScalarException;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.FabSortLot;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.adaptor.dao.FabSortAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;

/**
 * @author ravi
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class AMSDataParser extends JobHandler implements AdaptorConstants
{
    private static Logger m_parserLogger    = null;
    private String m_dataOutputDir          = null;

    private HashMap<String, FabSortLot> m_fabWipDataMap        = new HashMap<String, FabSortLot>();
    private HashMap<String, ShippedLot> m_fabShipDataMap       = new HashMap<String, ShippedLot>();

    public AMSDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir( VENDOR_NAME_AMS, WIP_TYPE_FAB );
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_parserLogger = AdaptorUtils.getDataParserLogger( m_dataOutputDir, VENDOR_NAME_AMS );
            FabSortAdaptorDAO.setLogger( m_parserLogger );   // All the DAOs and Parser should be logging into same file
            ShippedLotDAO.setLogger( m_parserLogger );
            AdaptorUtils.setLogger( m_parserLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading/creating "+ VENDOR_NAME_AMS+ " output directory from database, Exception: " + se);
            throw se;
        }
    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main( String args[] ) throws Exception
    {
        try
        {
            new AMSDataParser().execute();
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    
    //Execute Method
    public void execute() throws Exception
	{
       AdaptorUtils.printHeader( VENDOR_NAME_AMS, CONSTANT_PARSER );

       File doneDestDir = new File( m_dataOutputDir + "/done" );

       File wipDataoutDir = new File( m_dataOutputDir );

       File[] fileList = wipDataoutDir.listFiles();

       if ( ( fileList == null ) || ( fileList.length <= 3 ) )
       {
           log( "No file found in directory: " + wipDataoutDir );
           throw new ScalarException( "No file found in directory: " + wipDataoutDir + "----\n\n" );
       }

       DBTransaction dbTransaction 	= null;
       ArrayList<File> successFileList   	= new ArrayList<File>();
       boolean success             	= false;

       try
       {
           for ( int i = 0; i < fileList.length; i++ )
           {
               if ( fileList[i].isDirectory() == true )
               {
                   continue;
               }

               if ( ( fileList[i].getName() != null ) && ( fileList[i].getName().trim().indexOf( AMSAdaptor.FILE_NAME_WIP_STATUS ) != -1 ) )
               {
               		parseDailyWipReport( fileList[i].getAbsolutePath() );
                    
                    successFileList.add( fileList[i] );
               }
               if ( ( fileList[i].getName() != null ) && ( fileList[i].getName().trim().indexOf( AMSAdaptor.FILE_NAME_SHIP_STATUS ) != -1 ) )
               {
               		parseShipReport( fileList[i].getAbsolutePath() );
                   
                    successFileList.add( fileList[i] );
               }
               success = true;
           }
       }
       catch ( Exception e )
       {
           success = false;
           log( "ERROR!! ERROR!! ERROR!! While parsing and storing File " + e );
           e.printStackTrace();
           throw e;
       }

        // to save the FAB lot tables
       try
       {
           if ( m_fabWipDataMap.isEmpty() == false )
           {
               log( " Updating Fab Lot Information" );
               FabSortAdaptorDAO.saveFabLot( null, m_fabWipDataMap.values().iterator(), WIP_TYPE_FAB, VENDOR_NAME_AMS );
               success = true;
           }
           else
           {
               FabSortAdaptorDAO.closeFabSortLot( dbTransaction, WIP_TYPE_FAB, VENDOR_NAME_AMS );
           }
      }
      catch (ScalarException se)
      {
          success = false;
          se.printStackTrace();
          log("ERROR!! ERROR!! ERROR!! Could not update Fab Lot information into database: " + se);
          throw se;
      }

      try
      {
        // Save shipping info -
        if ( m_fabShipDataMap.isEmpty() == false )
        {
            log( "Updating shipment Information" );
            ShippedLotDAO.saveShippedLot( null, m_fabShipDataMap.values().iterator() );
            success = true;
        }
      }
      catch ( Exception e )
      {
        success = false;
        log( "ERROR!! ERROR!! ERROR!! Could not update AMS Fab Shipping information into database: " + e );
        e.printStackTrace();
        throw e;
      }

      // To Close the Drop Out Lots
      AdaptorDAO.closeDropOutLots( VENDOR_NAME_AMS );
        
      // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
      AdaptorDAO.sendAllNotifications( VENDOR_NAME_AMS, true, true, true );


      int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( AMSAdaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR );

      // Update Adaptor_Run_Info table
      try
      {
            if ( success == true )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_PARSER, AMSAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id );
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
      }
      catch ( ScalarException se )
      {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_PARSER, AMSAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id );
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
       }
        // Move the successful files to 'done' directory
       if ( success )
       {
           AdaptorUtils.moveFilesToDone( successFileList, doneDestDir );
       }
   }//end of execute method


   	private void parseDailyWipReport( String fileName ) throws Exception
   	{
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result     = null;
   		String partNumber       = null;
        String lotNumber        = null;
        FabSortLot fabSortLot   = null;
        try
        {
            File fabWipFile = new File( fileName );
            if ( !fabWipFile.exists() )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }
             Parser parser = ParserFactory.getXLSParser( fabWipFile );

            ((XLSParserImpl)parser).setHeaderRowIdx(0);
            ((XLSParserImpl)parser).setDataStartRowIdx(1);
            
            log( "\nFound " + fileName );
            log( "\nParsing the file for Fab Wip Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for Fab Wip Report..." );

            result = parser.parse();

            while ( result.next() )
            {
                partNumber = result.getString("PARTID");
                lotNumber  = result.getString("LOTID");

                if ( partNumber != null && partNumber.trim().length() > 0 && lotNumber != null && lotNumber.trim().length() > 0 )
                {
                    fabSortLot = ( FabSortLot ) m_fabWipDataMap.get( partNumber + lotNumber );
                    if ( fabSortLot == null )
                    {
                        fabSortLot = new FabSortLot( VENDOR_NAME_AMS, WIP_TYPE_FAB );
                        m_fabWipDataMap.put( partNumber + lotNumber , fabSortLot );
                    }

                    int quantity = 0;

                    if( fabSortLot.getQtyIn() != null )
                    {
                        try
                        {
                            quantity = Integer.parseInt( fabSortLot.getQtyIn() );
                        }
                        catch ( NumberFormatException ignore )
                        {
                        }

                        quantity += result.getInt("AMOUNT_EXPECTED");
                    }
                    else
                    {
                        quantity = result.getInt("AMOUNT_EXPECTED");
                    }

                    if ( quantity > 0 )
                    {
                        fabSortLot.setLotId( lotNumber );
                        fabSortLot.setCustProduct( partNumber );
                        fabSortLot.setDateIn( StringUtils.formatDateToString(result.getDate("STARTTIME") ) );
                        fabSortLot.setQtyIn( quantity +"");
                        fabSortLot.setStage( result.getString("STAGE") );
                        fabSortLot.setFabLotNumber( lotNumber );
                        fabSortLot.setWsQty ( result.getInt("CURMAINQTY")+"" );
                        fabSortLot.setLotCategory( LOT_CATEGORY_TYPE_PROD );
                        fabSortLot.setShip_fcst_date( StringUtils.formatDateToString(result.getDate("CONFIRMED_DATE")  ) );
                        fabSortLot.setForcastedDateOut( StringUtils.formatDateToString(result.getDate("EXPECTED_DATE") ) );
                        fabSortLot.setOutLookDate( StringUtils.formatDateToString(result.getDate("CONFIRMED_DATE")  ) );
                        fabSortLot.setStagePosition( result.getString("LOCATION"));
                        fabSortLot.setFabLotNumber( lotNumber );
                        fabSortLot.setLotStatus( LOT_STATUS_RUNNING );
                    }
                }
            }
        }
        catch ( Exception ex )
        {   System.out.println("ERROR!!!ERROR!!! While Parsing the AMS Daily wip Sheet");
            ex.printStackTrace();
            throw ex;
        }
    }

    private void parseShipReport( String fileName ) throws Exception
   	{
   		if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result      = null;
        ShippedLot shippedLot    = null;
        String partNumber        = null;
        String lotNumber         = null;
        String shipDate          = null;
        try
        {
            File fabShipFile = new File( fileName );
            if ( !fabShipFile.exists() )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

             Parser parser = ParserFactory.getXLSParser( fabShipFile );

            ((XLSParserImpl)parser).setHeaderRowIdx(0);
            ((XLSParserImpl)parser).setDataStartRowIdx(1);
            log( "\nFound " + fileName );
            log( "\nParsing the file for Fab Ship Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for Fab Ship Report..." );

            result = parser.parse();

            while (result.next())
            {
                partNumber  = result.getString("Customer Part Number");
                lotNumber   = result.getString("Lot ID");
                shipDate    = StringUtils.formatDateToString(result.getDate("Ship Date:"));
                
                if (partNumber != null && partNumber.trim().length() > 0 && lotNumber != null && lotNumber.trim().length() > 0 )
                {
                    shippedLot = (ShippedLot) m_fabShipDataMap.get(lotNumber + partNumber + shipDate + result.getString("Destination") + result.getString("PO Number:") );

                    if (shippedLot == null)
                    {
                        shippedLot = new ShippedLot( VENDOR_NAME_AMS, LOCATION_TYPE_FAB );
                        m_fabShipDataMap.put(lotNumber + partNumber + shipDate+ result.getString("Destination") + result.getString("PO Number:") , shippedLot);
                    }
                    int quantity = 0;
                    if (shippedLot.getShipQty() != null)
                    {
                        try
                        {
                            quantity = Integer.parseInt(shippedLot.getShipQty());
                        }
                        catch (NumberFormatException ignore) {
                        }
                       quantity += result.getInt("Wafer Qty");
                    }
                    else
                    {
                        quantity = result.getInt("Wafer Qty");
                    }
                    if ( quantity > 0 )
                    {
                        shippedLot.setLotNumber(lotNumber);
                        shippedLot.setPartNumber(partNumber);
                        shippedLot.setShipDate(shipDate );
                        shippedLot.setShipQty(quantity + "");
                        shippedLot.setCustomerPO(result.getString("PO Number:") );
                        shippedLot.setFabLotNumber(lotNumber);
                        shippedLot.setInvoiceNumber(result.getString("Invoice Number:") );
                        //shippedLot.setHawb(result.getString("JSI HAWB"));
						shippedLot.setMawb(result.getString("MAWB"));
                        shippedLot.setNextLocation( result.getString("Destination"));
                    }
                }
            }
        }
        catch ( Exception ex )
        {   System.out.println("ERROR!!!ERROR!!! While Parsing the AMS Ship Sheet");
            ex.printStackTrace();
            throw ex;
        }
    }

    private static void log( String message )
    {
        if ( message == null ) return;

        if ( m_parserLogger != null )
        {
            synchronized ( m_parserLogger )
            {
                m_parserLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}

